<template>
	<view class="container" :style="pageHeight">
		<view class="box-1">
	 
			<scroll-view scroll-y style="height: 100%;" :scroll-into-view="intoView">
				<view class="talk-list" v-if="showType==1 && nowTxtMessage!=''&&isText==1">
					<view class="item flex-col" :class="'pull' ">
						<image src="/static/logo.png" mode="aspectFill" class="pic"></image>
						<view class="content">
							{{nowTxtMessage}}
						</view>
					</view>

				</view>

				<view class="talk-list2" v-if="showType==2">
					<view v-for="(item,index) in talkList" :key="item.id" :id="'msg-'+item.id">
						<view class="item flex-col" :class=" item.type == 1 ? 'push':'pull' ">
							<image :src="item.pic" mode="aspectFill" class="pic"></image>
							<view class="content">
								<template v-if="item.contentType === 'image'">
									<image :src="item.content" mode="widthFix" style="width: 400rpx;"></image>
								</template>
								<template v-else>
									{{item.content}}
								</template>
							</view>
						</view>
					</view>

				</view>
			</scroll-view>
		</view>
		<view class="box-2">
			<view class="flex-col" style="justify-content: flex-end

">
			<!-- 	<image src="@/static/yinliang-lv-button.png" style="width: 30px;height: 30px;"></image>
				<image @click="getHistory()" src="@/static/jilu-lv-button.png" style="width: 30px;height: 30px;">
				</image> -->
				
				<image v-if="isMusic==1"  @click="isMusicFun(2)" src="@/static/icon/声音.png"  style="width: 40px;height: 40px;" />
				<image v-if="isMusic==2" @click="isMusicFun(1)" src="@/static/icon/声音静音.png" style="width: 40px;height: 40px;" />
				<image  v-if="showType==2"  @click="showType=1" src="@/static/icon/退出.png"  style="width: 30px;height: 30px;" />
<!-- 				<image @click="isText=2" src="@/static/icon/隐藏文字.png" style="width: 40px;height: 40px;" /> -->
				<image v-if="showType==1"  src="@/static/icon/历史.png" @click="getHistory()"  style="width: 30px;height: 30px;" />

 			</view>

 
			<view  class="send-veiw" v-if="sendShow==1" >
				<wd-icon name="keyboard-collapse" size="30px" color="#fff" @click="sendShow=2"></wd-icon>
				 <button @touchstart="handleTouchStart" @touchend="handleTouchEnd" style="width: 80%;height: 100%;
				 background-color:#03BC03 ;line-height: 50px; color:#fff; font-size: 40rpx;">
					 按住说话
				 </button>
				<wd-toast />
				
				</view>
			<view v-if="sendShow==2"  class="send-veiw"
			  >
					 <wd-icon name="call" color="#fff" size="30px"
							@click="sendShow=1"></wd-icon>
					<input type="text"  style="color: #fff; font-size: 40rpx; width: 80%; margin-left: 20rpx;" v-model="content"
							placeholder="请输入聊天内容" placeholder-style="color:#DDD;">
							
							
			
						<wd-icon name="add-circle"  color="#fff"  size="30px" @tap="handleSendClick"></wd-icon>
 				
			 

			</view>

		</view>
	</view>
</template>

<script setup>
	
	import {
		getHistoryMsg
	} from "@/request/template-talk/history-msg.js";
	import {
		connectWebSocket,
		sendSocket,
		socketDataList
	} from "@/js/socket.js"
	import {
		compile,
		ref,
		watch
	} from 'vue';
	import {
		request
	} from "../../js/request";
	import { getUserInfo } from "../../js/user";
	import {
		useToast
	} from '@/node_modules/wot-design-uni'
	import { onShow,onLoad } from "@dcloudio/uni-app"
 	const toast = useToast();
	// 聊天列表数据
	const talkList = ref([]);
	const nowTxtMessage = ref('');
	const musicList = ref([]);
	// 发送内容
	const content = ref('');
	//1显示实时
	//2显示聊天记录
	const showType = ref(1);
	//声音
	let innerAudioContext = null;
 	let playMusic = false;
	let playText = false;
	const intoView = ref("");
	let recorderManager = uni.getRecorderManager();
	const sendShow = ref(1);
	 const isMusic=ref(1);
	 const isText=ref(1);
	 const recordAuth = ref(false) // 是否授权录音
 
		onLoad(()=>{
			getApp().globalData.token= uni.getStorageSync('user-token');
					
			getUserInfo();
		})
	 
		onShow(()=>{
			playMusic=false;
			playText=false;
			
			musicList.value=[];
 			
 			if(innerAudioContext!=null){
 				innerAudioContext.destroy();
			}
 			innerAudioContext= uni.createInnerAudioContext();
			innerAudioContext.autoplay = true;
			innerAudioContext.onEnded(() => {
				console.log('播放结束');
				if (musicList.value.length > 0) {
					console.log('继续播放'+innerAudioContext);
					
					playMusic = true;
					let audioUrl = musicList.value.shift()
					
					innerAudioContext.src = audioUrl;
					innerAudioContext.play();
				} else {
					playMusic = false;
				}
			
			});
			       innerAudioContext.onError((e) => {  
			            console.log('play voice error', e);  
			        }); 
 })
	
	

	watch(socketDataList.value, (newQueue) => {



		if (newQueue.length > 0) {
			// 取出并移除队列中的第一个消息
			// 将当前发送信息 添加到消息列表。
			let socketData = newQueue.shift();
			let message = socketData.message;
			let messageType = socketData.messageType;

			switch (messageType) {
				case 1:
					if (message == "stop") {
						playText = false;
						return;
					}

					if (playText == false) {
						// let data = {
						// 	"id":new Date().getTime(),
						// 	"content":message,
						// 	"contentType":"text",
						// 	"type":2,
						// 	"pic":"/static/logo.png"
						//  }

						// talkList.value.unshift(data);
						playText = true;
						nowTxtMessage.value = message;
					} else {
						nowTxtMessage.value = nowTxtMessage.value + message;
 						//	talkList.value[0].content= talkList.value[0].content+message;
					}
					break;
				case 2:
 					if(isMusic.value==1){
						musicList.value.push(message)
						console.log("music-message"+message+playMusic)
						if (playMusic == false) {
							playMusic = true;
							let audioUrl = musicList.value.shift()
							
						  
							innerAudioContext.src = audioUrl;
							innerAudioContext.play();
						
						}
					}
				

					break;
			}







		}
	});




	connectWebSocket();




	// 获取历史消息
	function getHistory() {
		showType.value = 2;
		let res = request({

			url: '/app/chatHistory/historyList'

		});

		res.then(success => {
			console.log(success);

			for (let index in success) {
				let dataAnswer = {
					"id": success[index].id + "-a",
					"content": success[index].answer,
					"contentType": "text",
					"type": 2,
					"pic": "/static/logo.png"
				}

				let dataQuestion = {
					"id": success[index].id + "-q",
					"content": success[index].question,
					"contentType": "text",
					"type": 1,
					"pic": "/static/logo.png"
				}

				talkList.value.unshift(dataAnswer);
				talkList.value.unshift(dataQuestion);
			}
			if (talkList.value.length > 0) {
				const selector = 'msg-' + talkList.value[0].id;
				intoView.value = selector;


				console.log(intoView.value);

			}
		}).catch(error => {
			console.log("catch" + error)
		});




	}

	// 发送信息
	function handleSendClick() {

		if (!content.value) {
			uni.showToast({
				title: '请输入有效的内容',
				icon: 'none'
			})
			return;
		}
		
		let   token = getApp().globalData.token;
		
	
		
		
		showType.value = 1;
		sendMessage(content.value, 'text');

		// 清空内容框中的内容
		content.value = '';
	}

	function sendMessage(content, contentType = 'text') {
		// 将当前发送信息 添加到消息列表。
		// let data = {
		// 	"id": new Date().getTime(),
		// 	content,
		// 	contentType,
		// 	"type": 1,
		// 	"pic": "/static/logo.png"
		// }
		musicList.value=[];
		talkList.value=[];
		sendSocket(content);
	}

	function sendVoice(content, length) {

		let socketResult = {
			"type": 2,
			"data": content,
			"length": length
		}
		console.log(socketResult);
		musicList.value=[];
		talkList.value=[];
		sendSocket(JSON.stringify(socketResult));
	}

 

 

	recorderManager.onStop(function(res) {
		console.log("onStop");
        showType.value = 1;
		let token = getApp().globalData.token;
		console.log(process.env.ENV_HTTP_URL + '/app/send/sendVoice'+token);
		uni.uploadFile({
			url: process.env.ENV_HTTP_URL + '/app/send/sendVoice',
			filePath: res.tempFilePath, // 直接上传临时文件
			name: 'audioFile',
			header: {
				'TOKEN_USER': token
			},
			formData: {
				type: 'mp3'
			},
			success: (res) => {
				console.log('uploadFile:', res.data);
				
					let data= res.data;
			 
			},
			fail: (err) => {
				console.error('上传失败:', err);
			}
		});

 
 
	});

	function handleTouchStart() {
	 
	 
	   if(!recordAuth.value) {
	     authorRecord()
	     
	   }
		if(recordAuth.value){
			// 使用组件库内部图标
			toast.loading({
				msg: "长按说话 松开关闭...",
				position: "middle"
			})
			
			console.log("handleTouchStart");
			
			recorderManager.start({
				format: 'mp3'
			});
		}
	
	 
		
		

	}

	function handleTouchEnd() {
		toast.close()

		console.log("handleTouchEnd");
		recorderManager.stop();
		console.log(recorderManager);

	}
	
	function isMusicFun(v){
		isMusic.value=v;
		if(v==2){
			console.log("静音");
			innerAudioContext.stop();
			
		}else{
			console.log("开启声音");
			
			innerAudioContext.play();
		}
	}
	// 录音授权
	function authorRecord() {
		  let authSetting =   uni.getSetting()
		        if (!authSetting['scope.record']) {
					
					uni.authorize({
					  scope: 'scope.record',//这里选择scope.(录音、位置、用户信息...都可以)
					  success() { // 允许授权
					    console.log('已授权录音');
					    recordAuth.value = true
					  },
					  fail() { // 拒绝授权
							
							//需要您打开录音权限，再次按住说话
						 
							
					    uni.showModal({
								  title: '麦克风功能未打开',
					      content: '需要您打开麦克风，再次按住说话',
					      confirmText: "确认",
					      confirmColor: '#1874f5',
					      cancelText: '取消',
					      success: (res) => {
					        if (res.confirm) {
					          uni.openSetting({ // opensetting 是调起设置页面的
												  success: (res) => {
					              // 获取设置授权的状态
					              const setting = res.authSetting;
					              recordAuth.value = setting['scope.record'] || false
					            }
					          })
					        } else {
					          return false;
					        }
					      }
					    })
					    return false;
					  }
					})
					
					
				}else{
					recordAuth.value = true
					
				}
		
	
	}
	
	
</script>

<style lang="scss">
	@import "../../lib/global.scss";

	page {
		background-color: #F3F3F3;
		font-size: 28rpx;
	}

	.container {
		height: calc(100vh - var(--window-top));
		display: flex;
		flex-direction: column;
		flex-wrap: nowrap;
		align-content: center;
		justify-content: space-between;
		align-items: stretch;
		background-image: url('https://g6666.online/files/fo3.jpg');
		background-size: cover;
		/* 或者其他背景大小设置 */
		background-position: center;
		/* 图片居中 */
	}



	.box-1 {
		width: 100%;
		height: 0;
		flex: 1 0 auto;
		box-sizing: content-box;

	}

	.box-2 {
		height: auto;
		z-index: 2;
		box-sizing: content-box;
		//background-color: #F3F3F3;

		/* 兼容iPhoneX */
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		>view {
			padding: 0 20rpx;
			height: 100rpx;
		}

		.content {
			background-color: #34d19d;
			height: 64rpx;
			padding: 0 20rpx;
			border-radius: 32rpx;
			font-size: 28rpx;

		}

		.send {
			background-color: #42b983;
			color: #fff;
			height: 64rpx;
			margin-left: 20rpx;
			border-radius: 32rpx;
			padding: 0;
			width: 120rpx;
			line-height: 62rpx;

			&:active {
				background-color: #5fc496;
			}
		}
	}

	.talk-list {
		padding-bottom: 20rpx;
		display: flex;
		// flex-direction: column-reverse;
		flex-wrap: nowrap;
		align-content: flex-start;
		justify-content: flex-end;
		// align-items: stretch;

		flex-direction: row-reverse;
		height: 100%;
		align-items: flex-end;


		// 添加弹性容器，让内容自动在顶部
		&::before {
			content: '.';
			display: inline;
			visibility: hidden;
			line-height: 0;
			font-size: 0;
			flex: 1 0 auto;
			height: 1px;
		}


		/* 消息项，基础类 */
		.item {
			padding: 20rpx 20rpx 0 20rpx;
			align-items: flex-start;
			align-content: flex-start;
			color: #333;

			.pic {
				width: 92rpx;
				height: 92rpx;
				border-radius: 50%;
				border: #fff solid 1px;
			}

			.content {
				padding: 20rpx;
				border-radius: 4px;
				max-width: 500rpx;
				word-break: break-all;
				line-height: 52rpx;
				position: relative;

			}

			/* 收到的消息 */
			&.pull {
				.content {
					margin-left: 32rpx;
					background-color: #fff;
					opacity: 0.9;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-right: 20rpx solid #fff;
						position: absolute;
						top: 30rpx;
						left: -18rpx;
					}
				}
			}

			/* 发出的消息 */
			&.push {
				/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
				flex-direction: row-reverse;

				.content {
					margin-right: 32rpx;
					background-color: #fff;
					opacity: 0.9;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-left: 20rpx solid #a0e959;
						position: absolute;
						top: 30rpx;
						right: -18rpx;
					}
				}
			}
		}
	}


	.talk-list2 {
		padding-bottom: 20rpx;
		display: flex;
		flex-direction: column-reverse;
		flex-wrap: nowrap;
		align-content: flex-start;
		justify-content: flex-end;
		align-items: stretch;

		// 添加弹性容器，让内容自动在顶部
		&::before {
			content: '.';
			display: inline;
			visibility: hidden;
			line-height: 0;
			font-size: 0;
			flex: 1 0 auto;
			height: 1px;
		}


		/* 消息项，基础类 */
		.item {
			padding: 20rpx 20rpx 0 20rpx;
			align-items: flex-start;
			align-content: flex-start;
			color: #333;

			.pic {
				width: 92rpx;
				height: 92rpx;
				border-radius: 50%;
				border: #fff solid 1px;
			}

			.content {
				padding: 20rpx;
				border-radius: 4px;
				max-width: 500rpx;
				word-break: break-all;
				line-height: 52rpx;
				position: relative;
			}

			/* 收到的消息 */
			&.pull {
				.content {
					margin-left: 32rpx;
					background-color: #fff;
					opacity: 0.9;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-right: 20rpx solid #fff;
						position: absolute;
						top: 30rpx;
						left: -18rpx;
					}
				}
			}

			/* 发出的消息 */
			&.push {
				/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
				flex-direction: row-reverse;

				.content {
					margin-right: 32rpx;
					background-color: #a0e959;
					opacity: 0.9;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-left: 20rpx solid #a0e959;
						position: absolute;
						top: 30rpx;
						right: -18rpx;
					}
				}
			}
		}
	}

	.button:active {
		position: relative;
	}

	.button:active::after {
		content: "";
		position: absolute;
		top: 50%;
		left: 50%;
		width: 0;
		height: 0;
		background-color: rgba(0, 0, 0, 0.2);
		border-radius: 100%;
		transform: translate(-50%, -50%) scale(0, 0);
		opacity: 1;
		transition: all 0.3s ease-out;
	}

	.button:active::after {
		width: 200px;
		height: 200px;
		opacity: 0;
		transform: translate(-50%, -50%) scale(1, 1);
	}
	
	.send-veiw{
		margin-left: 10rpx; margin-right: 10rpx; background-color: #03BC03; border-radius: 15px;
		  display: flex;
		  align-items: center; /* 垂直居中 */
 		  height: 100%; /* 确保有高度 */
	}
	
 
</style>